<template>
    <div style="margin: 0 50px">
        <!--搜索-->
        <el-row>
            <el-col :span="24">
                <div class="search">
                    <el-form :inline="true" :model="searchData" @keydown.enter.native="onSearch">
                        <el-form-item class="text" label="登录名">
                            <el-input
                                    placeholder="请输入登录名"
                                    v-model="searchData.username"
                                    size="small"
                                    clearable>
                            </el-input>
                        </el-form-item>
                        <el-form-item class="text" label="手机号码">
                            <el-input
                                    placeholder="请输入手机号码"
                                    v-model="searchData.phone"
                                    size="small"
                                    clearable>
                            </el-input>
                        </el-form-item>
                        <el-form-item class="text" label="状态">
                            <el-select v-model="searchData.state"
                                       size="small"
                                       placeholder="请选择状态"
                            >
                                <el-option
                                        v-for="item in state"
                                        :key="item.valueId"
                                        :label="item.valueName"
                                        :value="item.valueId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button icon="el-icon-search" size="mini" type="primary" @click="onSearch">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="onReset">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
        </el-row>
        <!--工具栏-->
        <el-row>
            <el-col :span="24">
                <div class="tools">
                    <el-button @click="handleAdd" size="mini" icon="el-icon-plus" type="primary">新增</el-button>
                    <el-button :disabled="editBtnDisable" size="mini" icon="el-icon-edit"
                               @click="handleEdit(null,{id:selected[0]})"
                               type="success">修改
                    </el-button>
                    <el-button :disabled="deleteBtnDisable" size="mini" icon="el-icon-delete"
                               @click="handleDeleteByIds(selected)"
                               type="danger">删除
                    </el-button>
                    <el-button :loading="exportBtnLoading" :disabled="exportBtnDisable" size="mini"
                               icon="el-icon-download" type="warning" @click="exportUsers">导出
                    </el-button>
                    <el-button size="mini"
                               icon="el-icon-upload"
                               type="info" @click="importDialogVisible=true">导入
                    </el-button>
                    <el-button :disabled="false" size="mini" icon="el-icon-refresh" @click="refresh">刷新
                    </el-button>
                </div>
            </el-col>
        </el-row>
        <!--表格-->
        <el-row>
            <el-col :span="24">
                <div style="width: auto;">
                    <el-table
                            :data="tableData"
                            @selection-change="selectionChange"
                            stripe
                            style="width: 100%;">
                        <el-table-column
                                type="selection"
                                align="center"
                                width="50">
                        </el-table-column>
                        <el-table-column
                                prop="id"
                                label="编号"
                                align="center"
                                width="80">
                        </el-table-column>
                        <el-table-column
                                prop="username"
                                align="center"
                                label="登录名">
                        </el-table-column>
                        <el-table-column
                                prop="name"
                                align="center"
                                label="姓名">
                        </el-table-column>
                        <el-table-column
                                label="性别"
                                align="center"
                                width="50">
                            <template slot-scope="scope">
                                    <span v-for="item in gender"
                                          v-if="item.valueId===scope.row.gender">
                                    {{item.valueName}}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="phone"
                                align="center"
                                label="电话号码">
                        </el-table-column>
                        <el-table-column
                                prop="idCard"
                                align="center"
                                label="身份证号码">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                label="状态"
                                width="70">
                            <template slot-scope="scope">
                                <span v-for="item in state"
                                      v-if="item.valueId===scope.row.state">
                                  <el-tag v-if="scope.row.state===1" type="success">{{item.valueName}}</el-tag>
                                  <el-tag v-if="scope.row.state===2" type="danger">{{item.valueName}}</el-tag>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="created"
                                align="center"
                                label="创建时间">

                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        type="text"
                                        icon="el-icon-edit"
                                        @click="handleEdit(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button
                                        size="mini"
                                        type="text"
                                        icon="el-icon-delete"
                                        @click="handleDelete(scope.$index, scope.row)">删除
                                </el-button>
                                &nbsp;
                                <el-dropdown size="mini">
                                    <el-button
                                            size="mini"
                                            type="text"
                                    >更多<i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item @click.native="resetPsw(scope.row.username)"><i
                                                class="el-icon-key"></i>重置密码
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="margin-top: 15px;text-align: right;">
                        <el-pagination
                                background
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="currentPage"
                                :page-sizes="[10,20,50,100, 200, 300, 400]"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                        </el-pagination>
                    </div>
                </div>
            </el-col>
        </el-row>

        <!--新增用户-->
        <el-dialog
                :close-on-click-modal="false"
                title="新增用户"
                :visible.sync="addDialogVisible">
            <el-form :inline="true" :model="addUser"
                     label-position="right"
                     label-width="90px">
                <el-form-item class="text" label="登录名">
                    <el-input
                            placeholder="请输入登录名"
                            v-model="addUser.username"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>
                <el-form-item class="text" label="密码">
                    <el-input
                            placeholder="请输入密码"
                            v-model="addUser.password"
                            type="password"
                            size="small"
                            show-password>
                    </el-input>
                </el-form-item>

                <el-form-item class="text" label="姓名">
                    <el-input
                            placeholder="请输入姓名"
                            v-model="addUser.name"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>

                <el-form-item class="text" label="性别">
                    <el-select v-model="addUser.gender"
                               size="small"
                               placeholder="请选择性别">
                        <el-option
                                v-for="item in gender"
                                :key="item.valueId"
                                :label="item.valueName"
                                :value="item.valueId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="text" label="电话号码">
                    <el-input
                            placeholder="请输入电话号码"
                            v-model="addUser.phone"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>

                <el-form-item class="text" label="身份证号码">
                    <el-input
                            placeholder="请输入身份证号码"
                            v-model="addUser.idCard"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>
                <el-form-item class="text" label="状态">
                    <el-select v-model="addUser.state"
                               size="small"
                               placeholder="请选择状态">
                        <el-option
                                v-for="item in state"
                                :key="item.valueId"
                                :label="item.valueName"
                                :value="item.valueId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="text" label="角色">
                    <el-select v-model="addUser.roleIds"
                               value-key="value"
                               size="small"
                               multiple
                               placeholder="请选择角色">
                        <el-option
                                v-for="item in roles"
                                :key="item.id"
                                :label="item.roleDesc"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleAddUser">确 定</el-button>
            </span>
        </el-dialog>

        <!--编辑用户-->
        <el-dialog
                :close-on-click-modal="false"
                title="编辑用户"
                :visible.sync="editDialogVisible">
            <el-form :inline="true" :model="editUser"
                     label-position="right"
                     label-width="90px">
                <el-form-item class="text" label="登录名">
                    <el-input
                            readonly
                            placeholder="请输入登录名"
                            v-model="editUser.username"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>
                <el-form-item class="text" label="姓名">
                    <el-input
                            placeholder="请输入姓名"
                            v-model="editUser.name"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>

                <el-form-item class="text" label="性别">
                    <el-select v-model="editUser.gender"
                               placeholder="请选择性别"
                               size="small">
                        <el-option
                                v-for="item in gender"
                                :key="item.valueId"
                                :label="item.valueName"
                                :value="item.valueId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="text" label="电话号码">
                    <el-input
                            placeholder="请输入电话号码"
                            v-model="editUser.phone"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>

                <el-form-item class="text" label="身份证号码">
                    <el-input
                            placeholder="请输入身份证号码"
                            v-model="editUser.idCard"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>
                <el-form-item class="text" label="状态">
                    <el-select v-model="editUser.state"
                               size="small"
                               placeholder="请选择状态">
                        <el-option
                                v-for="item in state"
                                :key="item.valueId"
                                :label="item.valueName"
                                :value="item.valueId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="text" label="角色">
                    <el-select v-model="editUser.roleIds"
                               size="small"
                               multiple
                               placeholder="请选择角色">
                        <el-option
                                v-for="item in roles"
                                :key="item.id"
                                :label="item.roleDesc"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleEditUser">确 定</el-button>
            </span>
        </el-dialog>
        <!--导入用户-->
        <el-dialog
                :close-on-click-modal="false"
                width="400px"
                title="导入"
                :visible.sync="importDialogVisible">
            <el-upload
                    align="center"
                    class="upload-demo"
                    drag
                    :headers="{
                    'Authorization': token
                    }"
                    name="file"
                    :on-success="uploadSuccess"
                    :on-error="uploadError"
                    :action="uploadPath">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">
                    <div>
                        只能上传xls/xlsx文件!
                    </div>
                    <el-button type="text" size="mini" @click="getImportExcelHandle">导入模板下载</el-button>
                </div>
            </el-upload>
        </el-dialog>
    </div>
</template>

<script>
    import {
        userList,
        getUserById,
        addUser,
        deleteUser,
        updateUser,
        deleteUsers,
        resetPassword, userExport, getImportExcel
    } from "../../../../api/user";
    import {rolesDict} from "../../../../api/role";
    import {queryByTypeCode} from "../../../../api/dictionary";
    import {onlyFormat} from "../../../../utils/date";
    import fileDownload from 'js-file-download';
    import {getApiPath, getToken} from '../../../../utils/common';

    export default {
        name: "User",
        data() {
            return {
                searchData: {
                    username: "",
                    phone: "",
                    state: "",
                },
                tableData: [],
                addUser: {
                    username: '',
                    name: '',
                    password: '',
                    gender: 1,
                    phone: '',
                    idCard: '',
                    state: 1,
                    roleIds: []
                },
                editUser: {
                    id: '',
                    username: '',
                    name: '',
                    gender: 0,
                    phone: '',
                    idCard: '',
                    state: 0,
                    created: '',
                    roleIds: [],
                },
                total: 10,//总页数
                currentPage: 1,//当前页面
                pageSize: 10,//每页大小
                addDialogVisible: false,//显示添加模态框
                editDialogVisible: false,//显示修改模态框
                importDialogVisible: false,//显示导入模态框
                editBtnDisable: true,
                deleteBtnDisable: true,
                exportBtnDisable: true,
                exportBtnLoading: false,
                selected: [],
                roles: [],//角色字典
                gender: [],//性别字典
                state: [],//状态字典
                token: "",
                uploadPath: ""
            }
        },
        mounted() {
            this.getUserList()
            this.getRoles();
            this.getDict();
            this.uploadInit();
        },
        methods: {
            uploadInit() {
                let api = getApiPath();
                this.token = getToken();
                this.uploadPath = api + 'user/import'
            },
            //搜索
            async onSearch() {
                if (this.searchData.username.length === 0 &&
                    this.searchData.phone.length === 0 &&
                    this.searchData.state.length === 0) {
                    return false;
                }
                this.getUserList();
            },
            //搜索重置
            onReset() {
                this.searchData.username = "";
                this.searchData.phone = "";
                this.searchData.state = "";
                this.getUserList();
            },
            //添加按钮
            handleAdd() {
                this.addUser = {
                    username: '',
                    name: '',
                    password: '',
                    gender: 1,
                    phone: '',
                    idCard: '',
                    state: 1,
                    roleIds: []
                }
                this.addDialogVisible = true;
            },
            //刷新按钮
            refresh() {
                this.getUserList()
            },
            //编辑按钮
            async handleEdit(index, row) {
                let resp = await getUserById(row.id)
                this.editUser = resp.data
                this.$set(this.editUser, "roleIds", [])
                resp.data.roles.forEach(role => {
                    this.editUser.roleIds.push(role.id)
                })
                this.editDialogVisible = true
            },
            //提交编辑用户
            async handleEditUser() {
                let flag = false;
                Object.values(this.editUser).forEach(value => {
                    if (value == null || value === "") {
                        flag = true;
                    }
                })
                if (flag) {
                    this.$message.warning("请完整填写表单")
                    return false;
                }

                let user = JSON.parse(JSON.stringify(this.editUser))
                delete user.roles;
                delete user.permissions;
                let resp = await updateUser(user)
                if (resp.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.getUserList();
                    this.editDialogVisible = false
                } else {
                    this.$message({
                        type: 'error',
                        message: '修改失败：' + resp.message
                    });
                }
            },
            //删除按钮
            handleDelete(index, row) {
                console.log(index, row);
                this.$confirm('是否确认删除用户编号为"' + row.id + '"的数据项??', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let resp = await deleteUser(row.id)
                    if (resp.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getUserList();
                    } else {
                        console.log(resp)
                        this.$message({
                            type: 'error',
                            message: '删除失败：' + resp.message
                        });
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleDeleteByIds() {
                this.$confirm('是否确认删除用户编号为"' + this.selected + '"的数据项??', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let resp = await deleteUsers(this.selected)
                    if (resp.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getUserList();
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败：' + resp.message
                        });
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //获取用户列表
            async getUserList() {
                let bean = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    ...this.searchData
                }
                let resp = await userList(bean)
                this.tableData = resp.data.list;
                this.total = resp.data.total;
            },
            //页数改变
            handleSizeChange(val) {
                this.pageSize = val
                this.getUserList()
            },
            //翻页
            handleCurrentChange(val) {
                this.currentPage = val
                this.getUserList()
            },
            //获取角色
            async getRoles() {
                let resp = await rolesDict()
                this.roles = resp.data
            },
            async handleAddUser() {
                if (this.addUser.username.length === 0 ||
                    this.addUser.name.length === 0 ||
                    this.addUser.gender.length === 0 ||
                    this.addUser.phone.length === 0 ||
                    this.addUser.idCard.length === 0 ||
                    this.addUser.state.length === 0
                ) {
                    this.$message.warning("请完整填写表单")
                    return false;
                }
                let resp = await addUser(this.addUser)
                if (resp.code === 200) {
                    this.$message.success('添加成功')
                    this.getUserList()
                    this.addDialogVisible = false
                } else {
                    this.$message.error("添加失败：" + resp.message)
                }
            },
            // 获取字典信息
            async getDict() {
                let resp = await queryByTypeCode("gender");
                this.gender = resp.data
                resp = await queryByTypeCode("state");
                this.state = resp.data
            },
            selectionChange(selection) {
                if (selection.length === 0) {
                    this.editBtnDisable = true;
                    this.deleteBtnDisable = true;
                    this.exportBtnDisable = true;
                    this.selected.length = 0
                    console.log(this.selected)
                }

                if (selection.length > 0) {
                    this.deleteBtnDisable = false;
                    this.exportBtnDisable = false;
                    this.editBtnDisable = true;

                    this.selected.length = 0;
                    selection.forEach(item => {
                        this.selected.push(item.id)
                    })
                }
                if (selection.length === 1) {
                    this.editBtnDisable = false;
                }
            },
            resetPsw(username) {
                this.$prompt('请输入新密码', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /^\S{6,}$/,
                    inputErrorMessage: '不少于六位字符'
                }).then(async ({value}) => {
                    let resp = await resetPassword(username, value);
                    if (resp.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '重置成功！'
                        });
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消输入'
                    });
                });
            },
            async exportUsers() {
                let data = await userExport(this.selected);
                fileDownload(data, "用户信息表.xlsx");
            },
            //解析时间
            parseDate(time) {
                return onlyFormat(time);
            },

            uploadSuccess(resp) {
                if (resp.code === 200) {
                    if (resp.data.success > 0) {
                        this.$message.success(resp.data.success + "条数据导入成功！")
                        this.getUserList();
                    } else {
                        this.$message.info("导入失败")
                    }
                    this.$notify({
                        title: '导入结果',
                        duration: 30000,
                        dangerouslyUseHTMLString: true,
                        message: `检测到共有 <strong style="color: #000000">${resp.data.total}</strong> 条数据,<br/>
                            <strong style="color: #2ecc71">${resp.data.success}</strong> 条数据成功导入,<br/>
                            <strong style="color: #ff2200">${resp.data.total - resp.data.success}</strong> 条数据导入失败,<br/>`,
                        type: 'success'
                    });

                } else {
                    this.$message.error('导入失败')
                }
            },
            uploadError(e) {
                this.$message.error('导入失败')
            },
            async getImportExcelHandle() {
                let data = await getImportExcel()
                fileDownload(data, "用户信息导入模板.xlsx");
            }
        }
    }
</script>
<style scoped lang="scss">

</style>